<!--表单-->
<template>
  <div class="new-form">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      :disabled="disabled"
    >
      <el-divider content-position="left">基本信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="考勤组名称" prop="name" label-width="120px">
            <el-input
              v-model="form.name"
              placeholder="请输入考勤组名称"
              style="width: 200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="对应班次" prop="shiftId">
            <el-select v-model="form.shiftId" placeholder="请选择">
              <el-option
                v-for="item in timeShiftOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状 态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.label"
                :label="dict.value"
                >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="类 型" prop="attendanceType">
            <el-radio-group v-model="form.attendanceType">
              <el-radio
                v-for="dict in [
                  { label: '工作', value: 1 },
                  { label: '非工作', value: 2 }
                ]"
                :key="dict.label"
                :label="dict.value"
                >{{ dict.label }}
              </el-radio>
            </el-radio-group>
            <div style="color:#AFAFAF;font-size:10px">
              <el-icon class="el-icon-question" style="color:orange"></el-icon>
              休息、请假等无法来现场的属于非工作
            </div>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-divider content-position="left">打卡时间</el-divider>
      <el-row>
        <el-col :span="5" :offset="1">
          <el-button type="primary" @click="addNewUpWorkInfo"
            >添加上班打卡</el-button
          >
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="addNewDownWorkInfo"
            >添加下班打卡</el-button
          >
        </el-col>
        <el-col :span="12">
          <el-button type="default" icon="el-icon-refresh" @click="tempReset"
            >重置</el-button
          >
        </el-col>
      </el-row>
      <!-- 排班栏 -->
      <div style="height:300px;" v-if="workBars.length == 0">
        <el-empty description="暂无记录"></el-empty>
      </div>
      <div
        style="height:300px;overflow:hidden;overflow-y:scroll;margin-top:15px"
        v-else
      >
        <div class="work-time-items" v-for="(v, k) in workBars" :key="k">
          <div>第{{ v.sortNum }}次</div>
          <el-tag :type="v.type == 1 ? 'success' : 'warning'" effect="dark">{{
            v.type == 1 ? "上班" : "下班"
          }}</el-tag>
          <div>正常打卡范围</div>
          <div>
            <el-time-select
              :disabled="disabled"
              style="width:150px"
              placeholder="起始时间"
              v-model="v.startTime"
              :picker-options="{
                start: '06:00',
                step: '00:10',
                end: '21:30'
              }"
            >
            </el-time-select>
            <el-time-select
              :disabled="disabled"
              style="width:150px;margin-left:10px"
              placeholder="结束时间"
              v-model="v.endTime"
              :picker-options="{
                start: '06:00',
                step: '00:10',
                end: '21:30',
                minTime: v.startTime
              }"
            >
            </el-time-select>
          </div>
          <div>
            <el-checkbox v-model="v.nextDay">次日</el-checkbox>
          </div>
          <div @click="deleteItem(k)" class="delete-icon">
            <el-icon class="el-icon-delete"></el-icon>
          </div>
        </div>
      </div>
    </el-form>
    <div style="margin-top:15px;display:flex;justify-content:end">
      <el-button
        @click="submit"
        type="primary"
        :loading="loading"
        v-if="!disabled"
        >确定</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    timeShiftOptions: {
      type: Array,
      default: () => []
    },
    statusOptions: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    flag: {
      type: Boolean,
      default: false
    },
    initData: {
      type: Object,
      default: undefined
    }
  },
  data() {
    return {
      form: {
        status: 1,
        attendanceType: 1
      },
      rules: {
        name: [{ required: true, trigger: "blur", message: "考勤组名称必填" }]
        /* shiftId: [
          { required: true, trigger: "blur", message: "请选择对应班次" }
        ] */
      },
      baseInfo: {
        // 基础对象
        sortNum: 0,
        type: 1,
        startTime: undefined,
        endTime: undefined,
        nextDay: false
      },
      disabled: false, // 不可用标志
      upWorkTmp: [], // 上班信息缓存
      downWorkTmp: [], //下班信息缓存
      workBars: [] // 全部的排班信息
    };
  },
  watch: {
    flag() {
      this.form = { status: 1, attendanceType: 1 };
      this.tempReset();
    },
    initData: {
      handler(v) {
        if (!v.id) {
          return;
        }
        this.form = v;
        // 需要把上班的条目装到结构里面
        const temp = v.signItems;
        this.workBars = temp;
        temp.forEach(item => {
          if (item.type == 1) {
            this.upWorkTmp.push(item);
          } else {
            this.downWorkTmp.push(item);
          }
        });
        // 详情不可编辑
        this.disabled = v.disabled;
      },
      immediate: true
    }
  },
  methods: {
    // 取消表单
    cancel() {
      this.$emit("cancel");
    },
    // 确认提交表单
    submit() {
      this.$refs.form.validate(valid => {
        if (valid && this.validParameter()) {
          // 签到条目
          this.form["signItems"] = JSON.stringify(this.workBars);
          this.$emit("confirm", this.form);
        }
      });
    },
    // 验证设置是否正确
    validParameter() {
      if (this.form.attendanceType == 1 && this.downWorkTmp.length == 0) {
        this.$message.error("至少设置一个下班");
        return false;
      }
      for (let i = 0; i < this.workBars.length; i++) {
        if (!this.workBars[i].startTime || !this.workBars[i].startTime) {
          this.$message.error("请完善打卡范围");
          return false;
        }
      }
      return true;
    },
    // 这个要删除的，开发的时候用
    tempReset() {
      this.workBars = [];
      this.upWorkTmp = [];
      this.downWorkTmp = [];
    },
    // 添加上班打卡记录
    addNewUpWorkInfo() {
      const tmpBaseInfo = Object.assign({}, this.baseInfo);
      tmpBaseInfo.sortNum = this.upWorkTmp.length + 1; // tmp的长度就是排序
      this.workBars.push(tmpBaseInfo);
      this.upWorkTmp.push(tmpBaseInfo);
    },
    // 添加下班打卡记录
    addNewDownWorkInfo() {
      // 下班对应上班，没有上班就不能添加下班，检查是否成对
      if (
        this.upWorkTmp.length == this.downWorkTmp.length ||
        this.upWorkTmp.length == 0
      ) {
        this.$message.error("先添加上班记录");
        return;
      }
      const tmpBaseInfo = Object.assign({}, this.baseInfo);
      tmpBaseInfo.sortNum = this.downWorkTmp.length + 1;
      tmpBaseInfo.type = 2; // 下班类型
      this.workBars.push(tmpBaseInfo);
      this.downWorkTmp.push(tmpBaseInfo);
    },
    // 删除条目
    deleteItem(index) {
      this.$confirm("是否删除该条目?", "删除确认", {}).then(confirm => {
        if (confirm) {
          this.removeItemFromList(index);
        }
      });
    },
    // 移除条目
    removeItemFromList(index) {
      const item = this.workBars.splice(index, 1).pop();
      if (item.type == 1) {
        let idx = undefined;
        this.upWorkTmp.forEach((it, index) => {
          if (it.sortNum == item.sortNum) {
            idx = index;
          }
        });
        this.upWorkTmp.splice(idx, 1);
      } else {
        let idx = undefined;
        this.downWorkTmp.forEach((it, index) => {
          if (it.sortNum == item.sortNum) {
            idx = index;
          }
        });
        this.downWorkTmp.splice(idx, 1);
      }
    }
  }
};
</script>

<style scoped>
.work-time-items {
  background-color: #f8f8f8;
  margin-top: 15px;
  height: 40px;
  display: flex;
  align-items: center;
  padding: 0 15px;
  justify-content: space-around;
}

.delete-icon:hover {
  cursor: pointer;
}
</style>
